//
//  WorkOrderViewController.m
//  Recycling
//
//  Created by jzd on 2018/5/16.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "WorkOrderViewController.h"
#import "WaitOrdersTableVC.h"
#import "CompletionTableVC.h"
#import "WorkingTableController.h"

@interface WorkOrderViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewCons;
@property (weak, nonatomic) IBOutlet UIScrollView *backgroundScrollView;
@property (weak, nonatomic) IBOutlet UIView *sliderView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong,nonatomic) UIButton *currentSelectBut;
@property (weak, nonatomic) IBOutlet UIButton *firstBut;

@property(strong,nonatomic) WaitOrdersTableVC *wait;
@property(strong,nonatomic) WorkingTableController *working;
@property(strong,nonatomic) CompletionTableVC *complete;
@end

@implementation WorkOrderViewController
-(WaitOrdersTableVC *)wait{
    if (!_wait) {
        _wait = [[WaitOrdersTableVC alloc]init];
    }
    return _wait;
}
-(WorkingTableController *)working{
    if (!_working) {
        _working = [[WorkingTableController alloc]init];
    }
    return _working;
}
-(CompletionTableVC *)complete{
    if (!_complete) {
        _complete = [[CompletionTableVC alloc]init];
    }
    return _complete;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的工单";
    self.view.backgroundColor = BGCOLOR;
    self.topViewCons.constant = statsBarHeight+NavgationBarH;
    if (@available(iOS 11.0, *)) {
        self.backgroundScrollView.contentInsetAdjustmentBehavior =  UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self addchildVC];
    //默认选中第一个按钮
    self.currentSelectBut = self.firstBut;
}
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    for (UIView *subV in self.topView.subviews) {
        if ([subV isKindOfClass:[UIButton class]]) {
            self.sliderView.width = subV.width;
            self.sliderView.y = self.topView.height-1.5;
            break;
        }
    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 添加第0个子控制器的view
    [self addChildVcViewIntoScrollView:0];
    
    //为topView上的button 赋值正确的数量
    [self requestSureWaitNum];
}
-(void)requestSureWaitNum{
//    040001002：待接单
//    040001003：进行中
//    040001004：已完工
    NSDictionary *params = @{
                             @"pageno":@(1),
                             @"limit" : @(pageNum),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001002"
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {
                    int total = [[data objectForKey:@"total"] intValue];
                    [self.firstBut setTitle:[NSString stringWithFormat:@"待接单(%d)",total] forState:UIControlStateNormal];
                    [self.firstBut setTitle:[NSString stringWithFormat:@"待接单(%d)",total] forState:UIControlStateSelected];
                    [self requestSureWorkingNum];
                }
            }
        }
    }];
}
-(void)requestSureWorkingNum{
    //    040001002：待接单
    //    040001003：进行中
    //    040001004：已完工
    NSDictionary *params = @{
                             @"pageno":@(1),
                             @"limit" : @(pageNum),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001003"
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {
                    int total = [[data objectForKey:@"total"] intValue];
                    UIButton *sec = (UIButton *)[self.topView.subviews objectAtIndex:1];
                    [sec setTitle:[NSString stringWithFormat:@"进行中(%d)",total] forState:UIControlStateNormal];
                    [sec setTitle:[NSString stringWithFormat:@"进行中(%d)",total] forState:UIControlStateSelected];
                    [self requestSureCompletionNum];
                }
            }
        }
    }];
}
-(void)requestSureCompletionNum{
    //    040001002：待接单
    //    040001003：进行中
    //    040001004：已完工
    NSDictionary *params = @{
                             @"pageno":@(1),
                             @"limit" : @(pageNum),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001004"
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {
                    int total = [[data objectForKey:@"total"] intValue];
                    UIButton *third = (UIButton *)[self.topView.subviews objectAtIndex:2];
                    [third setTitle:[NSString stringWithFormat:@"已完成(%d)",total] forState:UIControlStateNormal];
                    [third setTitle:[NSString stringWithFormat:@"已完成(%d)",total] forState:UIControlStateSelected];
                }
            }
        }
    }];
}
-(void)addchildVC{
    
    [self addChildViewController:self.wait];
    [self addChildViewController:self.working];
    [self addChildViewController:self.complete];
    
    //KVO键值观察 控制topView上按钮的数量
    [self.wait addObserver:self forKeyPath:@"total" options:NSKeyValueObservingOptionNew context:nil];
    [self.working addObserver:self forKeyPath:@"total" options:NSKeyValueObservingOptionNew context:nil];
    [self.complete addObserver:self forKeyPath:@"total" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    NSString *value = [change valueForKey:@"new"];
    if ([keyPath isEqualToString:@"total"] && object == self.wait) {
        UIButton *third = (UIButton *)[self.topView.subviews objectAtIndex:0];
        [third setTitle:[NSString stringWithFormat:@"待接单(%@)",value] forState:UIControlStateNormal];
        [third setTitle:[NSString stringWithFormat:@"待接单(%@)",value] forState:UIControlStateSelected];
    }
    if ([keyPath isEqualToString:@"total"] && object == self.working) {
        UIButton *third = (UIButton *)[self.topView.subviews objectAtIndex:1];
        [third setTitle:[NSString stringWithFormat:@"进行中(%@)",value] forState:UIControlStateNormal];
        [third setTitle:[NSString stringWithFormat:@"进行中(%@)",value] forState:UIControlStateSelected];
    }
    if ([keyPath isEqualToString:@"total"] && object == self.complete) {
        UIButton *third = (UIButton *)[self.topView.subviews objectAtIndex:2];
        [third setTitle:[NSString stringWithFormat:@"已完成(%@)",value] forState:UIControlStateNormal];
        [third setTitle:[NSString stringWithFormat:@"已完成(%@)",value] forState:UIControlStateSelected];
    }
    
}



-(void)dealloc{
//    [self.wait removeObserver:self forKeyPath:@"total" context:nil];
//    [self.working removeObserver:self forKeyPath:@"total" context:nil];
//    [self.complete removeObserver:self forKeyPath:@"total" context:nil];
}

/**
 *  添加第index个子控制器的view到scrollView中
 */
- (void)addChildVcViewIntoScrollView:(NSUInteger)index
{
    UIViewController *childVc = self.childViewControllers[index];
    
    // 如果view已经被加载过，就直接返回
    if (childVc.isViewLoaded) return;
    
    // 取出index位置对应的子控制器view
    UIView *childVcView = childVc.view;
    
    // 设置子控制器view的frame
    childVcView.frame = CGRectMake(index * SJScreenW, 0, SJScreenW, SJScreenH);
    // 添加子控制器的view到scrollView中
    [self.containerView addSubview:childVcView];
}

/**
 *  点击标题按钮
 */
- (IBAction)titleButtonClick:(UIButton *)titleButton
{
    // 处理标题按钮点击
    [self dealTitleButtonClick:titleButton];
}
/**
 *  处理标题按钮点击
 */
- (void)dealTitleButtonClick:(UIButton *)titleButton
{
    // 切换按钮状态
    self.currentSelectBut.selected = NO;
    titleButton.selected = YES;
    self.currentSelectBut = titleButton;
    
    NSUInteger index = titleButton.tag;
    [UIView animateWithDuration:0.25 animations:^{
        // 处理下划线
        self.sliderView.centerX = titleButton.centerX;
        
        // 滚动scrollView
        CGFloat offsetX = self.backgroundScrollView.width * index;
        self.backgroundScrollView.contentOffset = CGPointMake(offsetX, self.backgroundScrollView.contentOffset.y);
    } completion:^(BOOL finished) {
        // 添加子控制器的view
        [self addChildVcViewIntoScrollView:index];
    }];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.sliderView.x = scrollView.contentOffset.x/3;
}
/**
 *  当用户松开scrollView并且滑动结束时调用这个代理方法（scrollView停止滚动的时候）
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 求出标题按钮的索引
    NSUInteger index = scrollView.contentOffset.x / self.backgroundScrollView.width;
    
    // 点击对应的标题按钮
    UIButton *titleButton = self.topView.subviews[index];
    //    [self titleButtonClick:titleButton];
    [self dealTitleButtonClick:titleButton];
}
@end
